package com.alex.megacj.checker;

import java.security.MessageDigest;
import java.util.Random;

public class SecurityUtils {

	private static final char[] hexChars = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

	public static String encodeSHA1(String str) {
		try {
			byte[] bytes = str.getBytes("iso-8859-1");
			MessageDigest messageDigest = MessageDigest.getInstance("SHA1");
			messageDigest.update(bytes);
			return hexStringFromBytes(messageDigest.digest());
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	public static String encodeMD5(String str) {
		try {
			byte[] bytes = str.getBytes("iso-8859-1");
			MessageDigest messageDigest = MessageDigest.getInstance("MD5");
			messageDigest.update(bytes);
			return hexStringFromBytes(messageDigest.digest());
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	private static String hexStringFromBytes(byte[] b) {
		StringBuilder hex = new StringBuilder(32);
		int msb;
		int lsb = 0;
		int i;
		for (i = 0; i < b.length; i++) {
			msb = ((int) b[i] & 0x000000FF) / 16;
			lsb = ((int) b[i] & 0x000000FF) % 16;
			hex.append(hexChars[msb]).append(hexChars[lsb]);
		}
		return hex.toString();
	}

	public static String genVerificationKey() {
		Random random = new Random();
		StringBuilder sb = new StringBuilder(64);
		for (int i = 0; i < 64; i++)
			sb.append((char) ('A' + random.nextInt(26)));
		return sb.toString();
	}

	public static String genPassword() {
		Random random = new Random();
		StringBuilder sb = new StringBuilder(10);
		for (int i = 0; i < 10; i++) {
			if (random.nextBoolean())
				sb.append((char) ('a' + random.nextInt(26)));
			else
				sb.append((char) ('A' + random.nextInt(26)));
		}
		return sb.toString();
	}
}
